package com.kadron.dao;

import java.util.List;

import javax.persistence.NoResultException;

import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

import com.kadron.entity.UserFavorites;
import com.kadron.entity.UserKadrons;

@AutoCreate
@BypassInterceptors
@Name("userFavoritesDAO")
public class KUserFavoritesDAO extends KDAO<UserKadrons> {

	@SuppressWarnings("unchecked")
	public List<UserKadrons> getAllFavorites(long userId) {
		StringBuffer buffer = new StringBuffer(
		"SELECT e_ FROM UserFavorites e_ WHERE e_.user.id = :user_id");
		javax.persistence.Query query = getEntityManager().createQuery(buffer.toString());
		query.setParameter("user_id", userId);
		return query.getResultList();
	}
	
	public Long getUserFavorites(long userId) {
		StringBuffer buffer = new StringBuffer(
		"SELECT COUNT(e_.id) FROM UserFavorites e_ WHERE e_.user.id = :user_id GROUP BY e_.user.id");
		javax.persistence.Query query = getEntityManager().createQuery(buffer.toString());
		query.setParameter("user_id", userId);
		try {
			return (Long) query.setMaxResults(1).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
	
	public UserFavorites getLastFavorite(long userId) {
		StringBuffer buffer = new StringBuffer(
		"SELECT e_ FROM UserFavorites e_ WHERE e_.user.id = :user_id ORDER BY e_.id DESC ");
		javax.persistence.Query query = getEntityManager().createQuery(buffer.toString());
		query.setParameter("user_id", userId);
		try {
			return (UserFavorites) query.setMaxResults(1).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
	
	public boolean isFavorite(long userId, long itemId) {
		StringBuffer buffer = new StringBuffer(
		"SELECT 1 FROM UserFavorites e_ WHERE e_.user.id = :user_id AND e_.item.id = :item_id");
		javax.persistence.Query query = getEntityManager().createQuery(buffer.toString());
		query.setParameter("user_id", userId);
		query.setParameter("item_id", itemId);
		try {			
			return query.setMaxResults(1).getSingleResult().equals(1);
		} catch (NoResultException e) {
			return false;
		}
	}
	
	public UserFavorites getFavorite(long userId, long itemId) {
		StringBuffer buffer = new StringBuffer(
		"SELECT e_ FROM UserFavorites e_ WHERE e_.user.id = :user_id AND e_.item.id = :item_id");
		javax.persistence.Query query = getEntityManager().createQuery(buffer.toString());
		query.setParameter("user_id", userId);
		query.setParameter("item_id", itemId);
		try {			
			return (UserFavorites) query.setMaxResults(1).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
	
}
